<?php
/**
 * Created by YuanXiShop.
 * User: YuanXi
 * Date: 2021/6/4 0004
 * Time: 17:14
 */

namespace home;


use JasonGrimes\Paginator;
use models\BaseDao;
use lmonkey\CatTree as CT;

class Product extends Home
{
    function index($id)
    {
        $db = new BaseDao();

        $product = $db->get('product','*',['id'=>$id]);

        $pid = $product['cid'];

        //面包屑导航
        $position = "您当前所在的位置：<a href='/'>首页</a>";

        $catss = $db->select('category','*',['ORDER'=>['ord'=>'ASC','id'=>'DESC']]);

        $category = CT::getList($catss);

        $catalls = $category[$pid];

        $path = ltrim($catalls['path'].','.$pid,'0,');

        foreach (explode(',',$path) as $v){
            $cattmp = $category[$v];

            $position .= " &gt; <a href='/plist/{$v}' title='{$cattmp['catname']}'>{$cattmp['catname']}</a>";
        }

        $position .= ' &gt; '.$product['name'];

        //分类和部分数据
        $catall = $db->select('category',['id','catname'],['pid'=>$pid,'ORDER'=>['ord'=>'ASC','id'=>'DESC']]);

        $catlist = [];

        foreach ($catall as $cat){
            //获取所有子分类
            $cat['subcats'] = $db->select('category',['id','catname'],['pid'=>$cat['id'],'ORDER'=>['ord'=>'ASC','id'=>'DESC']]);

            array_push($catlist,$cat);
        }

        //热销排行
        $childs = trim($catalls['childs']) =='' ? $pid : $catalls['childs'].','.$pid;
        if ($childs == 0){
            $selllists = $db->select('product',['id','name','logo','money','smoney'],['state'=>1,'ORDER'=>['sellnum'=>'DESC'],'LIMIT'=>6]);
        }else{
            $selllists = $db->select('product',['id','name','logo','money','smoney'],['cid'=>explode(',',$childs),'state'=>1,'ORDER'=>['sellnum'=>'DESC'],'LIMIT'=>6]);
        }
        //咨询记录
        $ask_list = $db->select('ask','*',['pid'=>$id,'ORDER'=>['atime'=>'DESC']]);

        $this->assign('ask_list',$ask_list);

        //评价记录
        $comment_list = $db->select('comment','*',['pid'=>$id,'ORDER'=>['atime'=>'DESC']]);

        $this->assign('comment_list',$comment_list);

        //售后服务
        $pagetext = $db->get('page',['content(pagetext)'],['id'=>13]);

        $this->assign($pagetext);

        $this->assign('catlist',$catlist);

        $this->assign('selllists',$selllists);

        $this->assign('position',$position);



        $this->assign($product);

        $this->assign('title',$product['name']);

        $this->display('product/index');

        $db->update('product',['clicknum[+]'=>1],['id'=>$id]);
    }

    /**
     * @param int $pid 当前查找分类ID
     */
    function plist($pid = 0)
    {
        $db = new BaseDao();

        //面包屑导航
        $position = "您当前所在的位置：<a href='/'>首页</a>";

        $catss = $db->select('category','*',['ORDER'=>['ord'=>'ASC','id'=>'DESC']]);

        $category = CT::getList($catss);

        $catalls = $category[$pid];

        $path = ltrim($catalls['path'].','.$pid,'0,');

        foreach (explode(',',$path) as $v){
            $cattmp = $category[$v];

            $position .= " &gt; <a href='/plist/{$v}' title='{$cattmp['catname']}'>{$cattmp['catname']}</a>";
        }

        $this->assign('position',$position);

        //分类和部分数据
        $catall = $db->select('category',['id','catname'],['pid'=>$pid,'ORDER'=>['ord'=>'ASC','id'=>'DESC']]);

        $catlist = [];

        foreach ($catall as $cat){
            //获取所有子分类
            $cat['subcats'] = $db->select('category',['id','catname'],['pid'=>$cat['id'],'ORDER'=>['ord'=>'ASC','id'=>'DESC']]);

            array_push($catlist,$cat);
        }

        //热销排行
        $childs = trim($catalls['childs']) =='' ? $pid : $catalls['childs'].','.$pid;
        if ($childs == 0){
            $selllists = $db->select('product',['id','name','logo','money','smoney'],['state'=>1,'ORDER'=>['sellnum'=>'DESC'],'LIMIT'=>6]);
        }else{
            $selllists = $db->select('product',['id','name','logo','money','smoney'],['cid'=>explode(',',$childs),'state'=>1,'ORDER'=>['sellnum'=>'DESC'],'LIMIT'=>6]);
        }




        //主题数据

        $num = $_GET['num'] ?? 1;
        $prosql =[];
        $where =[];
        //搜索条件
        if($pid != 0 ) {
            $where['cid'] = explode(',', $childs);
        }




        if(!empty($_GET['keyword'])){
            $where['name[~]'] = $_GET['keyword'];
            $name = '&keyword='.$_GET['keyword'];
            $this->assign('name',$name);
        }

        if(!empty($_GET['orderby']) || $_GET['orderby'] !='' ) {
            list($filed, $value) = explode('_', $_GET['orderby']);
            $prosql['ORDER'][$filed] .= strtoupper($value);
            $orderby='&orderby='.$_GET['orderby'];
        }else {
            $prosql['ORDER'] = ['cid'=>'ASC',"id" => "DESC"];
        }

        $this->assign('get',$_GET);

        $totalItems = $db->count('product',$where);//总页面数
        $itemsPerPage = 12;//每页显示多少条数据
        $currentPage = $num;//当前页是第几页
        $urlPattern = '/plist/'.$pid.'?num=(:num)'.$name.$orderby;

        $paginator = new Paginator($totalItems, $itemsPerPage, $currentPage, $urlPattern);

        //从第几页开始
        $start = ($currentPage-1) * $itemsPerPage;
        $prosql['LIMIT'] = [$start,$itemsPerPage];

        $prosql = array_merge($prosql,$where);

        $data = $db->select('product',['id','name','logo','money','smoney'],$prosql);
        // $data = $db->debug()->select('product',['id','name','logo','money','smoney'],$prosql);

        //排序
        $this->assign('pid',$pid);
        $this->assign('order',$_GET);

        $this->assign('data',$data);
        $this->assign('fpage',$paginator);

        $this->assign('selllists',$selllists);
        $this->assign('catlist',$catlist);
        $this->assign('title',$catalls['catname']);
        $this->display('product/plist');
    }

    /**
     * 添加收藏
     */
    function collectadd()
    {
        //商品id
        $collect['pid'] = $_GET['pid'];
        $collect['uid'] = $_SESSION['id'];


        $db = new BaseDao();
        $show = '';
        //判断是否已经收藏
        if($db->count('collect',['uid'=>$collect['uid'],'pid'=>$collect['pid']]) > 0){
            $show = '抱歉，你已经收藏了该商品，请不要重复收藏';
        }else{
            $collect['atime'] = time();
            if($db->insert('collect',$collect)){
                $db->update('product',['collectnum[+]'=>1],['id'=>$collect['pid']]);
                $show = '商品收藏成功..';
            }else{
                $show = '商品收藏失败';
            }
        }

        echo json_encode(['show'=>$show]);
        exit;
    }

    /**
     * 添加评价
     */
    function commentadd()
    {
        $db = new BaseDao();

        $comment['content'] = $_POST['content'];
        $comment['uid'] = $_SESSION['id'];
        $comment['pid'] = $_POST['pid'];
        $comment['uname'] = $_SESSION['name'];
        $comment['atime'] = time();
        $comment['uip'] = getClientIP();

        if ($_POST['do_submit']){
            if($db->insert('comment',$comment)){

                $db->update('product',['commentnum[+]'=>1],['id'=>$comment['pid']]);

                $atime = date('Y-m-d H:s',$comment['atime']);
                $commentText = htmlspecialchars($comment['content']);
$html = <<<html
<ul>
    <li class="fl">会员：{$comment['uname']}</li>
    <li class="fr">评价日期：{$atime}</li>
</ul>
<div class="pingjia font14">{$commentText}</div>
html;


                $result = true;
            }else{
                $result = false;
                $html = '';
            }
        }
        echo json_encode(['result'=>$result,'html'=>$html]);
    }
    //添加咨询
    function askadd()
    {
        $db = new BaseDao();

        $ask['asktext'] = $_POST['asktext'];
        $ask['uid'] = $_SESSION['id'];
        $ask['pid'] = $_POST['pid'];
        $ask['uname'] = $_SESSION['name'];
        $ask['atime'] = time();
        $ask['uip'] = getClientIP();

        if ($_POST['do_submit']){
            if($db->insert('ask',$ask)){

                $db->update('product',['asknum[+]'=>1],['id'=>$ask['pid']]);

                $atime = date('Y-m-d H:s',$ask['atime']);
                $askText = htmlspecialchars($ask['asktext']);
$html = <<<html
<ul>
    <li class="fl">会员：{$ask['uname']}</li>
    <li class="fr">评价日期：{$atime}</li>
</ul>
<div class="pingjia font14">{$askText}</div>
html;


                $result = true;
            }else{
                $result = false;
                $html = '';
            }
        }
        echo json_encode(['result'=>$result,'html'=>$html]);
    }
}